package com.boomer.controller;

import com.boomer.entity.FileSystem;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class FileController {

    @Autowired
    Redisson redisson;

    @Bean
    public Redisson redisson() {

        Config config = new Config();
        config.useSingleServer().setAddress("redis://192.168.234.131:6379").setDatabase(0);
        return (Redisson) Redisson.create(config);
    }

    @RequestMapping("/upload")
    @ResponseBody
    public FileSystem upload(MultipartFile fname) throws IOException, MyException {

        RLock rLock = redisson.getLock("fileUpload");
        rLock.lock(30, TimeUnit.SECONDS);

        FileSystem fileSystem = null;
        try {
            fileSystem = new FileSystem();
            String originalFilename = fname.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            String newFileName = UUID.randomUUID().toString() + "." + suffix;
            File toSaveFile = new File("D:/upload/" + newFileName);
            fname.transferTo(toSaveFile);
            String newFilePath = toSaveFile.getAbsolutePath();

            ClientGlobal.initByProperties("config/fastdfs-client.properties");
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer = trackerClient.getConnection();
            StorageServer storageServer = null;
            StorageClient1 client1 = new StorageClient1(trackerServer, storageServer);
            NameValuePair[] list = new NameValuePair[1];
            list[0] = new NameValuePair("fileName", originalFilename);
            String fileId = client1.upload_file1(newFilePath, suffix, list);
            trackerServer.close();

            fileSystem.setFileId(fileId);
            fileSystem.setFileName(originalFilename);
            fileSystem.setFilePath(fileId);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
        }

        return fileSystem;
    }
}
